package icu.cocoon.system.handler;


import icu.cocoon.dao.base.Resp;
import icu.cocoon.security.exception.LoginException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;

/**
 * @author xce
 * @date 2019/10/23 15:29
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

  @ExceptionHandler(HttpClientErrorException.class)
  public Resp<?> HttpClientErrorExceptionHandler(HttpClientErrorException e){
    if (e.getRawStatusCode()==401){
      return Resp.error("无权限");
    }
    return Resp.error(e.getMessage());
  }

  @ExceptionHandler(IllegalArgumentException.class)
  public Resp<String> illegalArgumentExceptionHandler(IllegalArgumentException e) {
    return Resp.error(e.getMessage());
  }


  @ExceptionHandler(MethodArgumentNotValidException.class)
  public Resp<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
    preHandler(e);
    BindingResult result = e.getBindingResult();
    List<ObjectError> list = result.getAllErrors();
    String resultStr = list.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(
        ";"));
    log.error(resultStr);
    return Resp.error(resultStr);
  }

  @ExceptionHandler(BindException.class)
  public Resp<String> bindExceptionHandler(BindException e){
    preHandler(e);
    BindingResult result = e.getBindingResult();
    List<ObjectError> list = result.getAllErrors();
    String resultStr = list.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(
        ";"));
    log.error(resultStr);
    return Resp.error(resultStr);

  }

  @ExceptionHandler(LoginException.class)
  public Resp<String> loginExceptionHandler(LoginException e) {
    preHandler(e);
    return Resp.error("登录异常");
  }

  @ExceptionHandler(Exception.class)
  public Resp<String> publicException(Exception e) {
    preHandler(e);
    return Resp.error(e.getMessage());
  }

  private void preHandler(Exception e) {
    log.error("异常class：{}", e.getClass());
    e.printStackTrace();
  }


}
